<template>
  <div class="sales-stats-page">
    <!-- 页面标题 -->
    <van-nav-bar
      title="销售购买统计"
      left-arrow
      @click-left="$router.back()"
      fixed
      placeholder
    />
    


    <!-- 统计概览卡片 -->
    <div class="stats-overview">
      <van-grid :column-num="2" :gutter="16">
        <van-grid-item>
          <div class="stat-card sales">
            <div class="stat-label">销售总额</div>
            <div class="stat-value">¥{{ formatAmount(overview.totalSales) }}</div>
            <div class="stat-trend" :class="overview.salesTrend >= 0 ? 'up' : 'down'">
              {{ overview.salesTrend >= 0 ? '+' : '' }}{{ overview.salesTrend }}%
            </div>
          </div>
        </van-grid-item>
        <van-grid-item>
          <div class="stat-card purchase">
            <div class="stat-label">购买总额</div>
            <div class="stat-value">¥{{ formatAmount(overview.totalPurchase) }}</div>
            <div class="stat-trend" :class="overview.purchaseTrend >= 0 ? 'up' : 'down'">
              {{ overview.purchaseTrend >= 0 ? '+' : '' }}{{ overview.purchaseTrend }}%
            </div>
          </div>
        </van-grid-item>
        <van-grid-item>
          <div class="stat-card profit">
            <div class="stat-label">净利润</div>
            <div class="stat-value">¥{{ formatAmount(overview.netProfit) }}</div>
            <div class="stat-trend" :class="overview.profitTrend >= 0 ? 'up' : 'down'">
              {{ overview.profitTrend >= 0 ? '+' : '' }}{{ overview.profitTrend }}%
            </div>
          </div>
        </van-grid-item>
        <van-grid-item>
          <div class="stat-card orders">
            <div class="stat-label">总订单数</div>
            <div class="stat-value">{{ overview.totalOrders }}</div>
            <div class="stat-trend" :class="overview.orderTrend >= 0 ? 'up' : 'down'">
              {{ overview.orderTrend >= 0 ? '+' : '' }}{{ overview.orderTrend }}%
            </div>
          </div>
        </van-grid-item>
      </van-grid>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <van-collapse v-model="activeFilter">
        <van-collapse-item title="筛选条件" name="filter">
          <!-- 时间范围 -->
          <van-field
            v-model="searchForm.timeRange"
            label="开始日期"
            readonly
            placeholder="选择开始日期"
            @click="showTimePicker = true"
          />
          
          <van-field
            v-model="searchForm.timeRange"
            label="结束日期"
            readonly
            placeholder="选择结束日期"
            @click="showEndDatePicker = true"
          />
          
          <!-- 类型筛选 -->
          <van-field
            v-model="searchForm.typeText"
            label="类型"
            readonly
            placeholder="选择类型"
            @click="showTypePicker = true"
          />
          
          <!-- 状态筛选 -->
          <van-field
            v-model="searchForm.statusText"
            label="状态"
            readonly
            placeholder="选择状态"
            @click="showStatusPicker = true"
          />
          
          <!-- 关键词搜索 -->
          <van-field
            v-model="searchForm.keyword"
            label="关键词"
            placeholder="订单号/商品标题"
            clearable
          />
          
          <!-- 操作按钮 -->
          <div class="filter-actions">
            <van-button type="primary" size="small" @click="handleSearch">搜索</van-button>
            <van-button size="small" @click="handleReset">重置</van-button>
          </div>
        </van-collapse-item>
      </van-collapse>
    </div>

    <!-- 趋势图表 -->
    <div class="trend-section">
      <van-tabs v-model="activeTrend" @change="handleTrendChange">
        <van-tab title="销售趋势" name="sales">
          <div class="chart-container">
            <div ref="salesChart" class="chart"></div>
          </div>
        </van-tab>
        <van-tab title="购买趋势" name="purchase">
          <div class="chart-container">
            <div ref="purchaseChart" class="chart"></div>
          </div>
        </van-tab>
      </van-tabs>
    </div>

    <!-- 记录列表 -->
    <div class="records-section">
      <div class="section-header">
        <h3>交易记录</h3>
        <van-button type="primary" size="small" @click="handleExport">导出数据</van-button>
      </div>
      
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="loadMore"
      >
        <van-cell
          v-for="record in records"
          :key="record.id"
          :title="record.title"
          :label="`${record.order_no} | ${formatDateTime(record.create_time)}`"
          @click="handleViewDetail(record)"
        >
          <template #value>
            <div class="record-info">
              <van-tag :type="getTypeTagType(record.type)" size="small">
                {{ getTypeText(record.type) }}
              </van-tag>
              <div class="record-amount" :class="record.type === 'sales' ? 'sales' : 'purchase'">
                {{ record.type === 'sales' ? '+' : '-' }}¥{{ formatAmount(record.amount) }}
              </div>
              <van-tag :type="getStatusTagType(record.status)" size="small">
                {{ getStatusText(record.status) }}
              </van-tag>
            </div>
          </template>
        </van-cell>
      </van-list>
    </div>

    <!-- 时间选择器 -->
    <van-popup v-model:show="showTimePicker" position="bottom">
      <van-date-picker
        v-model="searchForm.startDate"
        title="选择开始日期"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onStartDateConfirm"
        @cancel="showTimePicker = false"
      />
    </van-popup>
    
    <van-popup v-model:show="showEndDatePicker" position="bottom">
      <van-date-picker
        v-model="searchForm.endDate"
        title="选择结束日期"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onEndDateConfirm"
        @cancel="showEndDatePicker = false"
      />
    </van-popup>

    <!-- 类型选择器 -->
    <van-popup v-model:show="showTypePicker" position="bottom">
      <van-picker
        :columns="typeColumns"
        @confirm="onTypeConfirm"
        @cancel="showTypePicker = false"
      />
    </van-popup>

    <!-- 状态选择器 -->
    <van-popup v-model:show="showStatusPicker" position="bottom">
      <van-picker
        :columns="statusColumns"
        @confirm="onStatusConfirm"
        @cancel="showStatusPicker = false"
      />
    </van-popup>

    <!-- 详情对话框 -->
    <van-dialog
      v-model:show="detailDialogVisible"
      title="交易详情"
      :show-confirm-button="false"
      class="detail-dialog"
    >
      <div v-if="selectedRecord" class="detail-content">
        <van-cell-group>
          <van-cell title="订单号" :value="selectedRecord.order_no" />
          <van-cell title="类型">
            <van-tag :type="getTypeTagType(selectedRecord.type)">
              {{ getTypeText(selectedRecord.type) }}
            </van-tag>
          </van-cell>
          <van-cell title="金额">
            <span class="amount-text" :class="selectedRecord.type === 'sales' ? 'sales' : 'purchase'">
              {{ selectedRecord.type === 'sales' ? '+' : '-' }}¥{{ formatAmount(selectedRecord.amount) }}
            </span>
          </van-cell>
          <van-cell title="状态">
            <van-tag :type="getStatusTagType(selectedRecord.status)">
              {{ getStatusText(selectedRecord.status) }}
            </van-tag>
          </van-cell>
          <van-cell title="商品标题" :value="selectedRecord.title" />
          <van-cell title="创建时间" :value="formatDateTime(selectedRecord.create_time)" />
          <van-cell title="更新时间" :value="formatDateTime(selectedRecord.update_time)" />
        </van-cell-group>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { showToast, showLoadingToast, closeToast } from 'vant'
import { 
  getSalesStats, 
  getSalesRecords, 
  getSalesTrend, 
  getPurchaseTrend 
} from '@/api/sales-stats'

export default {
  name: 'SalesStats',
  setup() {
    // 响应式数据
    const activeFilter = ref(['filter'])
    const activeTrend = ref('sales')
    const loading = ref(false)
    const finished = ref(false)
    const showTimePicker = ref(false)
    const showEndDatePicker = ref(false)
    const showTypePicker = ref(false)
    const showStatusPicker = ref(false)
    const detailDialogVisible = ref(false)
    const selectedRecord = ref(null)
    
    // 图表引用
    const salesChart = ref(null)
    const purchaseChart = ref(null)
    
    // 数据
    const overview = ref({
      totalSales: 0,
      totalPurchase: 0,
      netProfit: 0,
      totalOrders: 0,
      salesTrend: 0,
      purchaseTrend: 0,
      profitTrend: 0,
      orderTrend: 0
    })
    
    const records = ref([])
    const currentPage = ref(0)
    const pageSize = ref(20)
    
    // 搜索表单
    const searchForm = reactive({
      startDate: null,
      endDate: null,
      timeRange: '',
      type: '',
      typeText: '',
      status: '',
      statusText: '',
      keyword: ''
    })
    
    // 选择器数据
    const typeColumns = [
      { text: '全部', value: '' },
      { text: '销售', value: 'sales' },
      { text: '购买', value: 'purchase' }
    ]
    
    const statusColumns = [
      { text: '全部', value: '' },
      { text: '已完成', value: 'completed' },
      { text: '进行中', value: 'processing' },
      { text: '已取消', value: 'cancelled' },
      { text: '已付款', value: 'paid' }
    ]
    
    // 计算属性
    const minDate = computed(() => {
      const date = new Date()
      date.setFullYear(date.getFullYear() - 1)
      return date
    })
    
    const maxDate = computed(() => new Date())
    
    // 方法
    const loadOverview = async () => {
      try {
        showLoadingToast('加载中...')
        const data = await getSalesStats({
          startDate: searchForm.startDate?.toISOString().split('T')[0],
          endDate: searchForm.endDate?.toISOString().split('T')[0]
        })
        overview.value = data || {
          totalSales: 0,
          totalPurchase: 0,
          netProfit: 0,
          totalOrders: 0,
          salesTrend: 0,
          purchaseTrend: 0,
          profitTrend: 0,
          orderTrend: 0
        }
        closeToast()
      } catch (error) {
        closeToast()
        console.error('加载统计数据失败:', error)
        // API失败时使用默认值，避免页面显示异常
        overview.value = {
          totalSales: 0,
          totalPurchase: 0,
          netProfit: 0,
          totalOrders: 0,
          salesTrend: 0,
          purchaseTrend: 0,
          profitTrend: 0,
          orderTrend: 0
        }
        showToast('加载统计数据失败，请检查网络连接')
      }
    }
    
    const loadRecords = async (isLoadMore = false) => {
      if (isLoadMore) {
        currentPage.value++
      } else {
        currentPage.value = 0
        records.value = []
        finished.value = false
      }
      
      try {
        loading.value = true
        const params = {
          page: currentPage.value,
          count: pageSize.value,
          type: searchForm.type,
          status: searchForm.status,
          keyword: searchForm.keyword,
          startDate: searchForm.startDate?.toISOString().split('T')[0],
          endDate: searchForm.endDate?.toISOString().split('T')[0]
        }
        
        const data = await getSalesRecords(params)
        
        if (isLoadMore) {
          records.value.push(...data.items || [])
        } else {
          records.value = data.items || []
        }
        
        // 如果没有数据或数据少于页面大小，标记为完成
        if (!data.items || data.items.length < pageSize.value) {
          finished.value = true
        }
      } catch (error) {
        console.error('加载记录失败:', error)
        // API失败时，显示错误信息并标记为完成，避免无限循环
        if (isLoadMore) {
          currentPage.value-- // 回退页码
        }
        finished.value = true // 标记为完成，停止加载
        showToast('加载记录失败，请检查网络连接')
      } finally {
        loading.value = false
      }
    }
    
    const loadTrend = async () => {
      try {
        const params = {
          type: 'daily',
          startDate: searchForm.startDate?.toISOString().split('T')[0],
          endDate: searchForm.endDate?.toISOString().split('T')[0]
        }
        
        if (activeTrend.value === 'sales') {
          const data = await getSalesTrend(params)
          // 这里可以集成图表库，暂时用console输出
          console.log('销售趋势数据:', data)
        } else {
          const data = await getPurchaseTrend(params)
          console.log('购买趋势数据:', data)
        }
      } catch (error) {
        console.error('加载趋势数据失败:', error)
        // 趋势数据加载失败不影响主要功能，只记录日志
      }
    }
    
    const handleSearch = () => {
      loadOverview()
      loadRecords()
      loadTrend()
    }
    
    const handleReset = () => {
      searchForm.dateRange = []
      searchForm.timeRange = ''
      searchForm.type = ''
      searchForm.typeText = ''
      searchForm.status = ''
      searchForm.statusText = ''
      searchForm.keyword = ''
      handleSearch()
    }
    
    const handleTrendChange = () => {
      loadTrend()
    }
    
    const loadMore = () => {
      loadRecords(true)
    }
    
    const handleViewDetail = (record) => {
      selectedRecord.value = record
      detailDialogVisible.value = true
    }
    
    const handleExport = async () => {
      try {
        showLoadingToast('导出中...')
        // 这里调用导出API
        closeToast()
        showToast('导出成功')
      } catch (error) {
        closeToast()
        showToast('导出失败')
        console.error('导出失败:', error)
      }
    }
    
    // 选择器确认事件
    const onStartDateConfirm = (value) => {
      searchForm.startDate = value
      updateTimeRange()
      showTimePicker.value = false
    }
    
    const onEndDateConfirm = (value) => {
      searchForm.endDate = value
      updateTimeRange()
      showEndDatePicker.value = false
    }
    
    const updateTimeRange = () => {
      if (searchForm.startDate && searchForm.endDate) {
        searchForm.timeRange = `${searchForm.startDate.toLocaleDateString()} - ${searchForm.endDate.toLocaleDateString()}`
      }
    }
    
    const onTypeConfirm = (value) => {
      searchForm.type = value.value
      searchForm.typeText = value.text
      showTypePicker.value = false
    }
    
    const onStatusConfirm = (value) => {
      searchForm.status = value.value
      searchForm.statusText = value.text
      showStatusPicker.value = false
    }
    
    // 工具方法
    const formatAmount = (amount) => {
      if (!amount) return '0.00'
      return Number(amount).toFixed(2)
    }
    
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      const date = new Date(dateTime)
      return date.toLocaleString()
    }
    
    const getTypeText = (type) => {
      const typeMap = {
        sales: '销售',
        purchase: '购买'
      }
      return typeMap[type] || type
    }
    
    const getTypeTagType = (type) => {
      return type === 'sales' ? 'success' : 'warning'
    }
    
    const getStatusText = (status) => {
      const statusMap = {
        completed: '已完成',
        processing: '进行中',
        cancelled: '已取消',
        paid: '已付款'
      }
      return statusMap[status] || status
    }
    
    const getStatusTagType = (status) => {
      const typeMap = {
        completed: 'success',
        processing: 'primary',
        cancelled: 'danger',
        paid: 'success'
      }
      return typeMap[status] || 'default'
    }
    
    // 生命周期
    onMounted(() => {
      // 加载真实数据
      loadOverview()
      loadRecords()
      loadTrend()
    })
    
    return {
      // 响应式数据
      activeFilter,
      activeTrend,
      loading,
      finished,
      showTimePicker,
      showEndDatePicker,
      showTypePicker,
      showStatusPicker,
      detailDialogVisible,
      selectedRecord,
      salesChart,
      purchaseChart,
      overview,
      records,
      
      // 表单数据
      searchForm,
      typeColumns,
      statusColumns,
      
      // 计算属性
      minDate,
      maxDate,
      
      // 方法
      loadOverview,
      loadRecords,
      loadTrend,
      handleSearch,
      handleReset,
      handleTrendChange,
      loadMore,
      handleViewDetail,
      handleExport,
      onStartDateConfirm,
      onEndDateConfirm,
      onTypeConfirm,
      onStatusConfirm,
      
      // 工具方法
      formatAmount,
      formatDateTime,
      getTypeText,
      getTypeTagType,
      getStatusText,
      getStatusTagType
    }
  }
}
</script>

<style scoped>
.sales-stats-page {
  padding-bottom: 20px;
}

.stats-overview {
  padding: 16px;
  background: #f7f8fa;
}

.stat-card {
  padding: 16px;
  border-radius: 8px;
  text-align: center;
  color: white;
}

.stat-card.sales {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-card.purchase {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-card.profit {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-card.orders {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-trend {
  font-size: 12px;
  opacity: 0.9;
}

.stat-trend.up {
  color: #52c41a;
}

.stat-trend.down {
  color: #ff4d4f;
}

.filter-section {
  margin: 16px;
}

.filter-actions {
  display: flex;
  gap: 12px;
  margin-top: 16px;
}

.trend-section {
  margin: 16px;
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.chart-container {
  height: 200px;
  padding: 16px;
}

.chart {
  width: 100%;
  height: 100%;
  background: #f7f8fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

.records-section {
  margin: 16px;
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.record-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: flex-end;
}

.record-amount {
  font-weight: bold;
}

.record-amount.sales {
  color: #52c41a;
}

.record-amount.purchase {
  color: #ff4d4f;
}

.detail-dialog {
  max-width: 90vw;
}

.detail-content {
  padding: 16px;
}

.amount-text {
  font-weight: bold;
}

.amount-text.sales {
  color: #52c41a;
}

.amount-text.purchase {
  color: #ff4d4f;
}
</style> 